define(function(require) {

  var $ = require("jquery");
  var _ = require("underscore");
  var Backbone = require("backbone");
  var MyModel = require("models/MyModel");
  var Utils = require("utils");
  var Parse = require("parse");
  var Autocomplete = require ("autocomplete");

  var PaginaRicercaMappa = Utils.Page.extend({

    constructorName: "PaginaRicercaMappa",

    model: MyModel,

    initialize: function() {
      // load the precompiled template
      this.template = Utils.templates.paginaricercamappa;

      
      // here we can register to inTheDOM or removing events
      // this.listenTo(this, "inTheDOM", function() {
      //   $('#content').on("swipe", function(data){
      //     console.log(data);
      //   });
      // });
      // this.listenTo(this, "removing", functionName);

      // by convention, all the inner views of a view must be stored in this.subViews
    },

    id: "searchmapview",
    className: "i-g page",

    events: {
       "touchend #query_ricerca": "goToSearch",
       "touchend #invio_query"  : "invioQuery"
    },

    render: function() {
      $(this.el).html(this.template());
      return this;
    },

    login: function(e){
       /*************************************************************************************
                                              login facebook
       **************************************************************************************/

      // This is called with the results from from FB.getLoginStatus().
      function statusChangeCallback(response) {
        console.log('statusChangeCallback');
        console.log(response);
        // The response object is returned with a status field that lets the
        // app know the current login status of the person.
        // Full docs on the response object can be found in the documentation
        // for FB.getLoginStatus().
        if (response.status === 'connected') {
          // Logged into your app and Facebook.

         
          Backbone.history.navigate("myview", { trigger: true });
          //testAPI();
        


        } else if (response.status === 'not_authorized') {
          // The person is logged into Facebook, but not your app.
          document.getElementById('status').innerHTML = 'Please log ' +
            'into this app.';
        } else {
          // The person is not logged into Facebook, so we're not sure if
          // they are logged into this app or not.
          
          document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';

          // Backbone.history.navigate("login", { trigger: true });

        }
      }

      // This function is called when someone finishes with the Login
      // Button.  See the onlogin handler attached to it in the sample
      // code below.
      function checkLoginState() {
        FB.getLoginStatus(function(response) {
          statusChangeCallback(response);
        });
      }

      window.fbAsyncInit = function() {
      FB.init({
        appId      : '445088995593662',
        cookie     : true,  // enable cookies to allow the server to access 
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.0' // use version 2.0
      });

      // Now that we've initialized the JavaScript SDK, we call 
      // FB.getLoginStatus().  This function gets the state of the
      // person visiting this page and can return one of three states to
      // the callback you provide.  They can be:
      //
      // 1. Logged into your app ('connected')
      // 2. Logged into Facebook, but not your app ('not_authorized')
      // 3. Not logged into Facebook and can't tell if they are logged into
      //    your app or not.
      //
      // These three cases are handled in the callback function.

      FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
      });

      };

      // Load the SDK asynchronously
      (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));

      // Here we run a very simple test of the Graph API after login is
      // successful.  See statusChangeCallback() for when this call is made.
      function testAPI() {
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me', function(response) {
          console.log('Successful login for: ' + response.name);
          document.getElementById('status').innerHTML =
            'Thanks for logging in, ' + response.name + '!';
        });
      }

/***************************************************************************************/


    },

/***************************************************************************************/
    //PRENDO IL RISULTATO DALL'INPUT E FACCIO LA QUERY AL DB
    invioQuery:function(){
      var Prodotti = Parse.Object.extend("Prodotti");
      var query = new Parse.Query(Prodotti);

      var prendiInput=$('[id="query_ricerca"]').val();
      query.equalTo("Titolo", prendiInput);
      query.find({
          success: function(Prodotti) {
              //alert(JSON.stringify(Prodotti));
              var array= new Array();
              var array1= new Array();
                for (var i = 0; i < Prodotti.length; i++) { 
                  array[i]=Prodotti[i];
                  array1[i]=array[i].get('Titolo');
                  alert("Hai cercato "+array1[i]);
                  //alert(Prodotti[i].id)  
                }
          },
          error: function(object, error) {
          alert("Error: " + error.code + " " + error.message);
          // The object was not retrieved successfully.
          // error is a Parse.Error with an error code and description.
          }
        });

    },



/***************************************************************************************/
    
    goToSearch: function(e) {
      
      //PROVA QUERY DATABASE
      var Prodotti = Parse.Object.extend("Prodotti");
      var query = new Parse.Query(Prodotti);
      
        query.find({
          success: function(Prodotti) {
              //alert(JSON.stringify(Prodotti));
              var array= new Array();
              var array1= new Array();
              for (var i = 0; i < Prodotti.length; i++) { 
                array[i]=Prodotti[i];
                array1[i]=array[i].get('Titolo');

                //alert(Prodotti[i].id)  
              }
              var options;
              options = {serviceUrl:'service/autocomplete.ashx',lookup:array1};
              $(function(){
              $('#query_ricerca').Autocomplete(options);
              });
              
          },
          error: function(object, error) {
          alert("Error: " + error.code + " " + error.message);
          // The object was not retrieved successfully.
          // error is a Parse.Error with an error code and description.
          }
        });
        //FINE PROVA QUERY DATABASE
     
      
    
      /*
      var Sidebar = Backbone.Model.extend({
        promptColor: function() {
          var cssColor = prompt("Please enter a CSS color:");
          this.set({color: cssColor});
        }
      });

      window.sidebar = new Sidebar;

      sidebar.on('change:color', function(model, color) {
        $('#sidebar').css({background: color});
      });

      sidebar.set({color: 'white'});

      sidebar.promptColor();
      */
      
      
      Backbone.history.navigate("searchView", {
        trigger: true
      });
     
    }
  });

  return PaginaRicercaMappa;

});